import axios, {InternalAxiosRequestConfig} from "axios"
import {util} from "../ts/util.ts";

const instance = axios.create({
    baseURL: 'http://127.0.0.1:9999', // 域名配置
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
    },
    withCredentials: true, // 跨域请求时是否需要使用凭证
    timeout: 30000
})

interface Result<T> {
    success: boolean
    msg: string
    value: T
}

// 请求拦截器
instance.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        return config
    },
    (error) => {
        // 错误抛到业务代码
        error.data = {}
        error.data.success = false
        error.data.msg = "服务器异常"
        return Promise.resolve(error)
    }
)

async function post<T>(url: string, data?: any): Promise<T> {
    const response = await instance.post<Result<T>>(url, data);
    if (!response.data.success) {
        util.msg?.error(response.data.msg);
        throw new Error(response.data.msg);
    } else {
        return response.data.value;
    }
}

export default post